package cn.kgc.base.service.impl;

import cn.kgc.base.service.FileService;
import cn.kgc.commons.config.OssFileConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

/**
 * <p>添加描述信息</p>
 *
 * @author 卢传琪
 */
@Service("fileService")
public class OssFileServiceImpl implements FileService {
    @Resource
    private OssFileConfig ossFileConfig;
    @Override
    public String upload(MultipartFile file, String userId, String fileName) {
        String  bucketName=ossFileConfig.getBucketName();
        String endpoint = ossFileConfig.getEndpoint();
        String accessKeyId = ossFileConfig.getAccessKeyId();
        String accessKeySecret = ossFileConfig.getAccessSecret();
        String objectName = ossFileConfig.getObjectName();
        String ossHost = ossFileConfig.getOssHost();
        OSS ossClient=null;

        try {
            //创建OSSClient实例
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //获得输入流
            InputStream inputStream = file.getInputStream();
            //重新给objectName属性赋值（文件夹的名字+文件的名字） images/pms/
            fileName=System.currentTimeMillis()+fileName;
            objectName=objectName+"/"+userId+"/"+fileName;
            //上传文件
            ossClient.putObject(bucketName,objectName,inputStream);
            ossHost=ossHost+objectName;
        } finally {
            //关闭OSSClient
            ossClient.shutdown();
            //返回图片的访问路径
            return ossHost;
        }
    }
}
